<?php
/**
 * tpshop
 * ============================================================================
 * * 版权所有 2015-2027 深圳搜豹网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.tp-shop.cn
 * ----------------------------------------------------------------------------
 * Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
 * ============================================================================
 * $Author: IT宇宙人 2015-08-10 $
 */
namespace Home\Controller;

class CartController extends BaseController {

    public $cartLogic; // 购物车逻辑操作类
    public $user_id = 0;
    public $user = array();
    /**
     * 初始化函数
     */
    public function _initialize(){
        parent::_initialize();
        $this->cartLogic = new \Home\Logic\CartLogic();

        if(session('?user'))
        {
            $user = session('user');
            $user = M('users')->where("user_id = {$user['user_id']}")->find();
            session('user',$user);  //覆盖session 中的 user
            $this->user = $user;
            $this->user_id = $user['user_id'];
            $this->assign('user',$user); //存储用户信息
            // 给用户计算会员价 登录前后不一样
            if($user){
                $user[discount] = (empty($user[discount])) ? 1 : $user[discount];
                M('Cart')->execute("update `__PREFIX__cart` set member_goods_price = goods_price * {$user[discount]} where (user_id ={$user[user_id]} or session_id = '{$this->session_id}') and prom_type = 0");
            }
        }



    }

    public function cart(){
        $this->display();
    }

    public function index(){
        $this->display('cart');
    }

    /**
     * ajax 将商品加入购物车
     */
    function ajaxAddCart()
    {
        $goods_id = I("goods_id"); // 商品id
        $goods_num = I("goods_num");// 商品数量
        $goods_spec = I("goods_spec"); // 商品规格
   /*     if(!$_SESSION['user']['user_id']){
            $result= array('status'=>-200,'msg'=>'请登录','result'=>'');
            exit(json_encode($result));
        }*/


        if(!$_SESSION['user']['is_member']&&$goods_id==68){
            $result= array('status'=>-100,'msg'=>'必须购买特殊会员','result'=>'');
            exit(json_encode($result));
        }




        $result = $this->cartLogic->addCart($goods_id, $goods_num, $goods_spec,$this->session_id,$this->user_id); // 将商品加入购物车
        exit(json_encode($result));
    }

    /**
     * ajax 删除购物车的商品
     */
    public function ajaxDelCart()
    {
        $ids = I("ids"); // 商品 ids
        $result = M("Cart")->where(" id in ($ids)")->delete(); // 删除id为5的用户数据
        $return_arr = array('status'=>1,'msg'=>'删除成功','result'=>''); // 返回结果状态
        exit(json_encode($return_arr));
    }


    /*
     * ajax 请求获取购物车列表
     */
    public function ajaxCartList()
    {

        $post_goods_num = I("goods_num"); // goods_num 购物车商品数量
        $post_cart_select = I("cart_select"); // 购物车选中状态
        $where = " session_id = '$this->session_id' "; // 默认按照 session_id 查询
        $this->user_id && $where = " user_id = ".$this->user_id; // 如果这个用户已经等了则按照用户id查询
        $cartList = M('Cart')->where($where)->getField("id,goods_id,goods_num,selected,prom_type,prom_id,member_goods_price,goods_price");

        //所有促销活动
        $now = time();
        $where_order = "end_time>$now and start_time<$now and is_close='1'";
        $prom_order = M('prom_order')->where($where_order)->order("id asc")->select();//当前只判断

        //筛选活动
        $promid_str='';
        $narr=array();
        foreach($cartList AS $a=>$b){

            foreach($prom_order AS $x=>$y){
                $goods_arr = explode(',',$y['goods_id']);

                if(in_array($b['goods_id'],$goods_arr)&&!in_array($y['id'],$narr)){
                    $narr[]=$y['id'];
                    $promid_str?$promid_str.=','.$y['id']:$promid_str.=$y['id'];
                }
            }
        }
        if($promid_str)
        {
            $where_order_n=$where_order.' and ( id in('.$promid_str.') or type in(0,1,2,3))';

        }else{
            $where_order_n=$where_order.' and type in(0,1,2,3)';
        }

        $prom_order = M('prom_order')->where($where_order_n)->order("id asc")->select();//当前只判断
        $this->assign('promname', $prom_order);


        if(I('hd_id'))
        {
            $hdid = I('hd_id'); // 促销类型
        }
        else
        {
            if($prom_order)
            {
                $hdid = $prom_order[0][id]; // 促销类型
            }
        }

        $this->assign('hd_id',$hdid); // 促销类型



        if($post_goods_num)
        {
            // 修改购物车数量 和勾选状态
            foreach($post_goods_num as $key => $val)
            {
                $data['goods_num'] = $val < 1 ? 1 : $val;

//                if($cartList[$key]['prom_type'] == 1) //限时抢购 不能超过购买数量
//                {
//                    $flash_sale = M('flash_sale')->where("id = {$cartList[$key]['prom_id']}")->find();
//                    $data['goods_num'] = $data['goods_num'] > $flash_sale['buy_limit'] ? $flash_sale['buy_limit'] : $data['goods_num'];
//                }
                $data['selected'] = $post_cart_select[$key] ? 1 : 0 ;
                if(($cartList[$key]['goods_num'] != $data['goods_num']) || ($cartList[$key]['selected'] != $data['selected'])) //判断数量以及选中状态变更的时候更保存数量及选中状态
                    M('Cart')->where("id = $key")->save($data);
            }
            $this->assign('select_all', $_POST['select_all']); // 全选框
        }

        $result = $this->cartLogic->cartList($this->user, $this->session_id,1,1,$hdid); // 选中的商品
        if(empty($result['total_price']))
            $result['total_price'] = Array( 'total_fee' =>0, 'cut_fee' =>0, 'num' => 0);

        $this->assign('cartList', $result['cartList']); // 购物车的商品
        $this->assign('total_price', $result['total_price']); // 总计
        $this->display('ajax_cart_list');
    }


    public function get_goods_sort($promcondition,$goods_num)

    {
        $count=count($promcondition)-1;
        if($goods_num<$promcondition[0]){
            $sort='l';
        }elseif($goods_num>=$promcondition[$count]){
            $sort='d';
        }else{
            foreach($promcondition as $key2 => $val2){
                if($goods_num<$val2){
                    $sort=$key2;
                    return $sort;
                }

            }
        }

        return $sort;
    }

    /**
     * 购物车第二步确定页面
     */
    public function cart2()
    {
        $hd_id=I('hd_id');
        $this->assign('hd_id', $hd_id); // 促销活动id

        /*
         if($this->user_id == 0)
             $this->error('请先登陆',U('Home/User/login'));
         */

        /*判断当前用户ID购物车是否有商品，否则将不能继续结算
        */
        if(!$this->user_id)
        {
            $arr['session_id']=$this->session_id;
            $arr['selected']=1;
            $c = M('Cart')->where($arr)->count();
            if(empty($c))
                $this->error ('妳的購物車沒有選中商品','Cart/cart');
        }
        else
        {
            if($this->cartLogic->cart_count($this->user_id,1) == 0 )
                $this->error ('妳的購物車沒有選中商品','Cart/cart');
        }
        $result = $this->cartLogic->cartList($this->user, $this->session_id,1,1,$hd_id); // 获取购物车商品


        $shippingList = M('Plugin')->where("`type` = 'shipping' and status = 1")->order('code asc')->select();// 物流公司

        /*登录情况读取优惠券信息*/
        if($this->user_id)
        {
            $Model = new \Think\Model(); // 找出这个用户的优惠券 没过期的
            $sql = "select c1.name,c1.id,c1.cateid,c1.money,c1.expression,c1.condition, c2.* from __PREFIX__coupon as c1 inner join __PREFIX__coupon_list as c2  on c2.cid = c1.id and c1.type in(0,1,2,3,4,5) and order_id = 0  where c2.uid = {$this->user_id}  and ".time()." < c1.use_end_time ";
            $couponList = $Model->query($sql);

            //优惠券筛选
            foreach($couponList AS $ke=>$va){
                $coupon=M('coupon')->where("id=".$va['cid'])->find();
                if($coupon['cateid']==1&&$result['total_price']['total_fee']<$coupon['condition'] ){
                    unset($couponList[$ke]);
                }elseif($coupon['cateid']==3&&$result['total_price']['total_fee']<$coupon['money']){
                    unset($couponList[$ke]);
                }
            }
            // 优惠券筛选 订单金额达到 condition 优惠券指定标准的
            $this->assign('couponList', $couponList); // 优惠券列表
        }


//        $this->assign('couponList', $couponList); // 优惠券列表
        $this->assign('shippingList', $shippingList); // 物流公司
        $this->assign('cartList', $result['cartList']); // 购物车的商品
        $this->assign('total_price', $result['total_price']); // 总计
        $this->assign('userstate', $this->user_id); // 用户状态
        $this->display();
    }

    /*
     * ajax 获取用户收货地址 用于购物车确认订单页面
     */
    public function ajaxAddress(){
        $model = M('UserAddress');
        if(!$this->user_id)
        {
            //array('sessionid_id'=>$this->session_id,'is_pickup'=>0)
            $address_list = $model->where(array('sessionid_id'=>$this->session_id,'is_pickup'=>0))->select();
        }
        else
        {
            $address_list = $model->where('user_id = '.$this->user_id.' AND is_pickup = 0')->select();
        }

        if($address_list){
            $area_id = array();
            foreach ($address_list as $val){
                $area_id[] = $val['province'];
                $area_id[] = $val['city'];
                $area_id[] = $val['district'];
                $area_id[] = $val['twon'];
            }
            $area_id = array_filter($area_id);
            $area_id = implode(',', $area_id);
            $regionList = M('region')->where("id in ($area_id)")->getField('id,name');
            $this->assign('regionList', $regionList);
        }
        $address_where['is_default'] = 1;

        if(!$this->user_id)
        {

            $c = $model->where(array('sessionid_id'=>$this->session_id,'is_default'=>1,'is_pickup'=>0))->count(); // 看看有没默认收货地址
        }
        else
        {
            $c = $model->where('user_id = '.$this->user_id.' AND is_default=1 AND is_pickup = 0')->count(); // 看看有没默认收货地址
        }
        if((count($address_list) > 0) && ($c == 0)) // 如果没有设置默认收货地址, 则第一条设置为默认收货地址
            $address_list[0]['is_default'] = 1;

        $this->assign('address_list', $address_list);
        $this->display('ajax_address');
    }

    public function test(){
        $user_id = 18991;
        echo crc32($user_id);
    }

    /**
     * @author dyr
     * @time 2016.08.22
     * 获取自提点信息
     */
    public function ajaxPickup()
    {
        $address_list = D('UserAddress')->getUserPickup($this->user_id);
        $province_id = I('province_id');
        $city_id = I('city_id');
        $district_id = I('district_id');
        if (empty($province_id) || empty($city_id) || empty($district_id)) {
            exit("<script>alert('参数错误');</script>");
        }
        $pickup_list = D('Pickup')->getPickupItemByPCD($province_id, $city_id, $district_id);
        $this->assign('pickup_list', $pickup_list);
        $this->assign('address_list', $address_list);
        $this->display('ajax_pickup');
    }

    /**
     * @author dyr
     * @time 2016.08.22
     * 更换自提点
     */
    public function replace_pickup()
    {
        $province_id = I('get.province_id');
        $city_id = I('get.city_id');
        $district_id = I('get.district_id');
        $region_model = M('region');
        $call_back = I('get.call_back');
        if (IS_POST) {
            echo "<script>parent.{$call_back}('success');</script>";
            exit(); // 成功
        }
        $address = array('province' => $province_id, 'city' => $city_id, 'district' => $district_id);
        $p = $region_model->where(array('parent_id' => 0, 'level' => 1))->select();
        $c = $region_model->where(array('parent_id' => $province_id, 'level' => 2))->select();
        $d = $region_model->where(array('parent_id' => $city_id, 'level' => 3))->select();
        $this->assign('province', $p);
        $this->assign('city', $c);
        $this->assign('district', $d);
        $this->assign('address', $address);
        $this->assign('call_back', $call_back);
        $this->display();
    }

    /**
     * @author dyr
     * @time 2016.08.22
     * 更换自提点
     */
    public function ajax_PickupPoint()
    {
        $province_id = I('province_id');
        $city_id = I('city_id');
        $district_id = I('district_id');
        $pick_up_model = D('Pickup');
        $pick_up_list = $pick_up_model->getPickupListByPCD($province_id,$city_id,$district_id);
        exit(json_encode($pick_up_list));
    }


    /**
     * ajax 获取订单商品价格 或者提交 订单
     */
    public function cart3(){
        $nosubmit =  I("nosubmit");
        $hd_id = I("hd_id"); //  促销活动id
        $address_id = I("address_id"); //  收货地址id
        $shipping_code =  I("shipping_code"); //  物流编号
        $invoice_title = I('invoice_title'); // 发票
        $couponTypeSelect =  I("couponTypeSelect"); //  优惠券类型  1 下拉框选择优惠券 2 输入框输入优惠券代码
        $coupon_id =  I("coupon_id"); //  优惠券id
        $couponCode =  I("couponCode"); //  优惠券代码
        $pay_points =  I("pay_points",0); //  使用积分
        $user_money =  I("user_money",0); //  使用余额
        $user_money = $user_money ? $user_money : 0;
        if(!$this->user_id)
        {
            $arr['session_id']=$this->session_id;
            $arr['selected']=1;
            $c = M('Cart')->where($arr)->count();

            if(empty($c))
            {
                exit(json_encode(array('status'=>-2,'msg'=>'妳的購物車沒有選中商品','result'=>null)));
            }
        }
        else
        {
            if($this->cartLogic->cart_count($this->user_id,1) == 0 )
            {
                exit(json_encode(array('status'=>-2,'msg'=>'妳的購物車沒有選中商品','result'=>null)));
            }
        }


        //if($this->cartLogic->cart_count($this->user_id,1) == 0 ) ; // 返回结果状态
//        if(!$address_id) exit(json_encode(array('status'=>-3,'msg'=>'請先填寫收貨人信息','result'=>null))); // 返回结果状态
//        if(!$shipping_code) exit(json_encode(array('status'=>-4,'msg'=>'請選擇物流信息','result'=>null))); // 返回结果状态
//        $address = M('UserAddress')->where("address_id = $address_id")->find();
        if($shipping_code!="smzt")
        {
            if(!$nosubmit)//判断假如不是提交订单不进行查询是否收货人
            {
                if(!$address_id) exit(json_encode(array('status'=>-3,'msg'=>'請先填寫收貨人信息','result'=>null))); // 返回结果状态
            }
            if($address_id)//有收货地址才读取
            {
                $address = M('UserAddress')->where("address_id = $address_id")->find();
            }
        }
        if(!$shipping_code) exit(json_encode(array('status'=>-4,'msg'=>'請選擇物流信息','result'=>null))); // 返回结果状态
//        if($this->user_id)
//        {
//            $order_goods = M('cart')->where("user_id = {$this->user_id} and selected = 1")->select();
//        }
//        else
//        {
//            $arr['session_id']=$this->session_id;
//            $arr['selected']=1;
//            $order_goods = M('cart')->where($arr)->select();
//        }

        $result_price = $this->cartLogic->cartList($this->user, $this->session_id,1,2,$hd_id); // 获取购物车商品
        $result=order_price($this->user_id,$result_price['result']['total_price'],$address,0,$pay_points,$user_money,$coupon_id,$couponCode);

//        $result = calculate_price($this->user_id,$order_goods,$shipping_code,0,$address[province],$address[city],$address[district],$pay_points,$user_money,$coupon_id,$couponCode);
        if($result_price['status'] < 0)
            exit(json_encode($result));



        // 订单满额优惠活动
        $car_price = array(
            'postFee'      => $result['result']['shipping_price'], // 物流费
            'couponFee'    => $result['result']['coupon_price'], // 优惠券
            'balance'      => $result['result']['user_money'], // 使用用户余额
            'pointsFee'    => $result['result']['integral_money'], // 积分支付
            'payables'     => $result['result']['order_amount'], // 应付金额
            'goodsFee'     => $result['result']['goods_price'],// 商品价格
//            'order_prom_id' => $result['result']['order_prom_id'], // 订单优惠活动id
            'order_prom_id' => $hd_id, // 订单优惠活动id
            'order_prom_amount' => $result['result']['order_prom_amount'], // 订单优惠活动优惠了多少钱
        );
        // 提交订单
        if($_REQUEST['act'] == 'submit_order')
        {
            if(empty($coupon_id) && !empty($couponCode))
                $coupon_id = M('CouponList')->where("`code`='$couponCode'")->getField('id');
            $result = $this->cartLogic->addOrder($this->user_id,$address_id,$shipping_code,$invoice_title,$coupon_id,$car_price,$hd_id); // 添加订单
            exit(json_encode($result));
        }
        $return_arr = array('status'=>1,'msg'=>'计算成功','result'=>$car_price); // 返回结果状态
        exit(json_encode($return_arr));
    }
    /**
     * ajax 获取订单商品价格 或者提交 订单
     * 已经用心方法 这个方法 cart9  准备作废
     */

    /*
     * 订单支付页面
     */
    public function cart4(){
        $order_id = I('order_id');
        $order = M('Order')->where("order_id = $order_id")->find();
        // 如果已经支付过的订单直接到订单详情页面. 不再进入支付页面
        if($order['pay_status'] == 1){
            $order_detail_url = U("Home/User/order_detail",array('id'=>$order_id));
            header("Location: $order_detail_url");
        }
        if($order['user_id'] != 1){

            $arr['order_id']=$order['order_id'];
            $c = M('sms_log')->where($arr)->count();
            if(!$c)
            {
                //$send = sendSMS($order['mobile'],$order['order_sn'],$order['order_id']);
                $OrderLogic = new \Home\Logic\OrderLogic();
                $send = $OrderLogic->sms_log($order['mobile'],$order['order_sn'],$order['order_id']);
            }
        }
        $paymentList = M('Plugin')->where("`type`='payment' and status = 1 and  scene in(0,2)")->select();
        $paymentList = convert_arr_key($paymentList, 'code');
        foreach($paymentList as $key => $val)
        {
            $val['config_value'] = unserialize($val['config_value']);
            if($val['config_value']['is_bank'] == 2)
            {
                $bankCodeList[$val['code']] = unserialize($val['bank_code']);
            }
        }

        $bank_img = include 'Application/Home/Conf/bank.php'; // 银行对应图片             
        $this->assign('paymentList',$paymentList);
        $this->assign('bank_img',$bank_img);
        $this->assign('mobilesn',$c);
        $this->assign('order',$order);
        $this->assign('bankCodeList',$bankCodeList);
        $this->assign('pay_date',date('Y-m-d', strtotime("+1 day")));
        $this->display();
    }


    public function order_detail(){
        $id = I('get.id');

        $map['order_id'] = $id;
        $map['user_id'] = $this->user_id;
        $order_info = M('order')->where($map)->find();
        $order_info = set_btn_order_status($order_info);  // 添加属性  包括按钮显示属性 和 订单状态显示属性


        if(!$order_info){
            $this->error('没有获取到订单信息');
            exit;
        }
        //获取订单商品

        $model = new \Home\Logic\UsersLogic();
        $data = $model->get_order_goods($order_info['order_id']);
        $order_info['goods_list'] = $data['result'];
        //$order_info['total_fee'] = $order_info['goods_price'] + $order_info['shipping_price'] - $order_info['integral_money'] -$order_info['coupon_price'] - $order_info['discount'];
        //获取订单进度条
        $sql = "SELECT action_id,log_time,status_desc,order_status FROM ((SELECT * FROM __PREFIX__order_action WHERE order_id = $id AND status_desc <>'' ORDER BY action_id) AS a) GROUP BY status_desc ORDER BY action_id";
        $items = M()->query($sql);
        $items_count = count($items);
        $region_list = get_region_list();

        $invoice_no = M('DeliveryDoc')->where("order_id = $id")->getField('invoice_no',true);
        $order_info[invoice_no] = implode(' , ', $invoice_no);
        //获取订单操作记录
        $order_action = M('order_action')->where(array('order_id'=>$id))->select();
        if($order_info['shipping_status'] == 1){
            $express = queryExpress($order_info['shipping_code'],$order_info['invoice_no']);
            $this->assign('express',$express);
        }
        $this->assign('order_status',C('ORDER_STATUS'));
        $this->assign('shipping_status',C('SHIPPING_STATUS'));
        $this->assign('pay_status',C('PAY_STATUS'));
        $this->assign('region_list',$region_list);
        $this->assign('return_order',$return_order);
        $this->assign('order_info',$order_info);
        $this->assign('order_action',$order_action);
        $this->assign('active','order_list');
        $this->display();
    }

    //ajax 请求购物车列表
    public function header_cart_list()
    {
        $cart_result = $this->cartLogic->cartList($this->user, $this->session_id,0,1);
        if(empty($cart_result['total_price']))
            $cart_result['total_price'] = Array( 'total_fee' =>0, 'cut_fee' =>0, 'num' => 0);

        $this->assign('cartList', $cart_result['cartList']); // 购物车的商品
        $this->assign('cart_total_price', $cart_result['total_price']); // 总计
        $template = I('template','header_cart_list');
        $this->display($template);
    }
}
